package org.springframework.samples.mvc.basic.business;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.samples.mvc.basic.model.Identifiable;
import org.springframework.samples.mvc.basic.model.ReflectionTableModel;
import org.springframework.samples.mvc.basic.model.UITableModel;

public class ExcelServiceReflection<T extends Identifiable> implements ExcelService<T> {

    private UITableModel model;
	private Class<T> clazz;

    public ExcelServiceReflection(Class<T> clazz) {
           this.clazz = clazz;
    }

    @Override
    public Workbook exportToExcel(List<T> objects) {
    	initModel(clazz, objects);
        Workbook file = new HSSFWorkbook();
        Sheet sheet = file.createSheet(model.getModelAttribute());
        createHeader(sheet);
        createRows(sheet);
        return file;
    }
    
	@Override
    public List<T> importFromExcel(Workbook doc) {
        return null;
    }
	
	private void initModel(Class<T> clazz2, List<T> objects) {
		if (model == null) {
			model = new ReflectionTableModel<T>(clazz, objects);
		}
	}

    private void createRows(Sheet sheet) {
    	int excelRow = 1;
		for (int row = 0; row < model.getNumberOfRows(); row++, excelRow++) {
			Row excelrow = sheet.createRow(excelRow);
			for (int col = 0; col < model.getNumberOfColumns(); col++) {
				Cell cell = excelrow.createCell(col);
				if (getValueFromModel(row, col) != null) {
					cell.setCellValue(getValueFromModel(row, col)); 
				}
			}
		}
	}

	private String getValueFromModel(int row, int col) {
		Object valueAt = model.getValueAt(row, col);
		if (valueAt == null) {
			return null;
		}
		return valueAt.toString();//TODO Change toString to something meaningfull
	}

	private void createHeader(Sheet sheet) {
    	Row row = sheet.createRow(0);
        for (int i = 0; i < model.getNumberOfColumns(); i++) {
            row.createCell(i).setCellValue(model.getFieldLabels()[i]);
        }
    }

}
